# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################


"""
Supporting file upload
文件上传

"""


from time import sleep
from flask import Blueprint, request
import os
import utils.message.response as response
import datetime as dt
import utils.common.log as log
import utils.wraps.urlcost as urlcost
import utils.common.initres as initres
import utils.common.func as func
import uuid
import subprocess

if initres.COS_TYPE :
    import utils.oss.cos as oss   
else :
    import utils.oss.oss as oss


upload_module = Blueprint("upload", __name__, url_prefix="/api/v1/account/upload")

UPDATE_ALLOWED_EXTENSIONS = {"mp4", "mp3", "png", "jpg", "jpeg", "aac"}


def update_allowed_file(filename):
    return "." in filename and (
        filename.rsplit(".", 1)[1].lower() in UPDATE_ALLOWED_EXTENSIONS
        or (filename.rsplit(".", 2)[-2] + "." + filename.rsplit(".", 2)[-1])
        in UPDATE_ALLOWED_EXTENSIONS
    )


@upload_module.route("/", methods=["POST"])
@urlcost.cost_count_wraps
def upload():
 
    if request.method == "POST":

        # check if the post request has the file part
        if "file" not in request.files:
            return response.make_response_1001()

        file = request.files["file"]
        # if user does not select file, browser also
        # submit an empty part without filename
        if update_allowed_file(file.filename) is False:
            return response.make_response_1002()
        if file.filename == "":
            return response.make_response_1001()
        # elif allowed_file(file.filename) == False:
        #     return response.make_response_1002()

        if file:
            root, extension = os.path.splitext(file.filename)
            filename = initres.UPLOADPATH + str(uuid.uuid1()) + extension
            file.save(filename)
            dic = {
                "path": "http://127.0.0.1:33033/file/" + filename.split("/")[-1],
                "uploadtime": dt.datetime.now().strftime("%F %T"),
            }
            return response.make_response_success(dic)
        return """
        <!doctype html>
        <title>Upload new File</title>
        <h1>Upload new File</h1>
        <form method=post enctype=multipart/form-data action="/webapi/v1/system/upload">
        <input type=file name=file>
        <input type=submit value=Upload>
        </form>
        """

 
@upload_module.route("/templatexxx", methods=["POST"])
@urlcost.cost_count_wraps
def template_upload():
     
    if request.method == "POST":

        # check if the post request has the file part
        if "file" not in request.files:
            return response.make_response_1001()
        file = request.files["file"]
        # if user does not select file, browser also
        # submit an empty part without filename
        if update_allowed_file(file.filename) is False:
            return response.make_response_1002()
        if file.filename == "":
            return response.make_response_1001()
        if file:
            root, extension = os.path.splitext(file.filename)
            filename = initres.UPLOADPATH + str(uuid.uuid1()) + extension
            file.save(filename)

            if not os.path.exists(filename):
                print("fail")
            else:
                print("sucess")

            if filename.split(".")[1] == "mp3":   
                cmd = 'exiftool {} |grep Duration|grep approx'.format(
                    filename
                )  
                # res = os.popen(cmd)
                # res1 = res.readlines()
                res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                res1 = res.stdout.readlines()
                #res1 = Duration                        : 0:00:44 (approx)
                #特殊的Duration                        : 24.99 s (approx)
                if not b's' in res1[0]:
                    tmp = res1[0].decode('utf8').split('(')[0].split(':')
                    duration = (
                        float(tmp[-1])
                        + int(tmp[-2]) * 60
                    )
                else:
                    tmp = res1[0].decode('utf8').split(':')[1].split('s')[0]
                    duration = float(tmp)
                acccmd1 = "".format(
                    filename, filename.split(".")[0] + ".mp3"
                )  
                # accres3 = os.popen(acccmd1)
                # accres4 = accres3.readlines()
                oss.upload_webRes(filename)   
                filename = oss.upload_webRes(
                    filename.split(".")[0] + ".mp3"
                )  
                print(filename)
                dic = {
                    "path": filename,
                    "uploadtime": dt.datetime.now().strftime("%F %T"),
                    "duration": duration,
                }
                return response.make_response_success(dic)
            elif filename.split(".")[1] == "jpg" or filename.split(".")[1] == "aac":
                filename = oss.upload_webRes(filename)
                dic = {
                    "path": filename,
                    "uploadtime": dt.datetime.now().strftime("%F %T"),
                }
                return response.make_response_success(dic)
            else:
                bfcmd = "cp {} {} ".format(
                    filename, filename.split(".")[0] + "1.mp4"
                )
                print(bfcmd)
                bfres = os.popen(bfcmd)
                bfres1 = bfres.readlines()
                print(bfres1)
                cmd = 'exiftool {} |grep Duration '.format(
                    filename.split(".")[0] + "1.mp4"
                )
                print(cmd)
                # res = os.popen(cmd)
                # res1 = res.readlines()
                res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
                res1 = res.stdout.readlines()
                # duration = float(res1[0][0:-2].split(":")[-1])
                tmp = res1[0].decode('utf8').split('s')[0].split(':')
                duration = float(tmp[-1])
                filename = oss.upload_webRes(filename.split(".")[0] + "1.mp4")
                dic = {
                    "path": filename,
                    "uploadtime": dt.datetime.now().strftime("%F %T"),
                    "duration": duration,
                }

                return response.make_response_success(dic)

        return """
        <!doctype html>
        <title>Upload new File</title>
        <h1>Upload new File</h1>
        <form method=post enctype=multipart/form-data action="/webapi/v1/system/upload">
        <input type=file name=file>
        <input type=submit value=Upload>
        </form>
        """


@upload_module.route("/webres", methods=["POST"])
@urlcost.cost_count_wraps
def webres_upload():
    
    if request.method == "POST":

        # check if the post request has the file part
        if "file" not in request.files:
            return response.make_response_1001()

        file = request.files["file"]
        # if user does not select file, browser also
        # submit an empty part without filename
        if update_allowed_file(file.filename) is False:
            return response.make_response_1002()
        if file.filename == "":
            return response.make_response_1001()
        # elif allowed_file(file.filename) == False:
        #     return response.make_response_1002()

        if file:
            root, extension = os.path.splitext(file.filename)

            filename = initres.UPLOADPATH + str(uuid.uuid1()) + extension
            file.save(filename)
            filename = oss.upload_webRes(filename)

            dic = {"path": filename, "uploadtime": dt.datetime.now().strftime("%F %T")}

            return response.make_response_success(dic)
        return """
        <!doctype html>
        <title>Upload new File</title>
        <h1>Upload new File</h1>
        <form method=post enctype=multipart/form-data action="/webapi/v1/system/upload">
        <input type=file name=file>
        <input type=submit value=Upload>
        </form>
        """
